package com.devplatform.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.devplatform.constants.DataVoCodeConstant;
import com.devplatform.pojo.user.RolePermission;
import com.devplatform.pojo.user.User;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.user.IUserService;
import com.devplatform.service.user.RolePermissionService;
import com.devplatform.util.JwtUtil;
import com.devplatform.util.UserContextHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {
    private final JwtUtil jwtUtil;
    private final IUserService userService;
    private final ObjectMapper objectMapper;
    private final RolePermissionService rolePermissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        log.info(path + "进入拦截器");
        //放行预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //检查token存在
        String token = request.getHeader("token");
        if (token == null) {
            //开放特例，允许无token访问此路径
            if (path.startsWith("/api/article/getList/")) {
                return true;
            }
            log.info(path + "无token");
            error(response, DataVoCodeConstant.TOKEN_IS_NULL, "无token");
            return false;
        }
        Claims claims;
        try {
            claims = jwtUtil.extractAllClaims(token);
        } catch (MalformedJwtException e) {
            error(response, DataVoCodeConstant.TOKEN_IS_INVALID, "token无效");
            return false;
        }
        //检查token过期
        if (jwtUtil.isTokenExpired(token)) {
            log.info(path + "token过期");
            error(response, DataVoCodeConstant.TOKEN_IS_EXPIRED, "token过期");
            return false;
        }
        //检查token中的用户id是否存在
        Long id = claims.get("userId", Long.class);
        User user = userService.getById(id);
        if (user == null) {
            log.info(path + "用户不存在");
            error(response, DataVoCodeConstant.USER_IS_NOT_EXIST, "用户不存在");
            return false;
        }
        //检查用户是否有权限访问
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getPath, path);
        RolePermission rolePermission = rolePermissionService.getOne(wrapper);
        if (rolePermission != null) {
            if (rolePermission.getRoleId() > claims.get("role", Integer.class)) {
                error(response, DataVoCodeConstant.USER_NOT_PERMISSION, "用户无访问权限");
                return false;
            }
        }

        //检查用户是否被封禁
        int status = user.getUserStatusId();
        if (status != 0) {
            log.info(path + "用户状态非正常");
            error(response, DataVoCodeConstant.USER_IS_ABNORMAL, "用户状态非正常");
            return false;
        }
        UserContextHolder.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserContextHolder.clear();
    }

    private void error(HttpServletResponse response, Integer code, String msg) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(DataVo.error(code, msg)));
    }
}
